package models

import (
	"errors"
	"fmt"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type User struct {
	BaseModel       `xorm:"extends"`
	Name            string `json:"name"`
	DeptSn          string `json:"dept_sn"`
	Mobile          string `json:"mobile"`
	DeptName        string `json:"dept_name"`
	Code            string `json:"code"` // 工号
	Openid          string `json:"openid"`
	UnitRoleSn      string `xorm:"-" json:"unit_role_sn"`
	AccompanyUnitSn string `json:"accompany_unit_sn" xorm:"-"`
}

type Accompany struct {
	Code   string `json:"code"` // 工号
	UnitSn string `json:"unit_sn"`
}

type UserQuery struct {
	Limit  int    `json:"limit"`
	Offset int    `json:"offset"`
	Code   string `json:"code"`
	Name   string `json:"name"`
}

func (pm *User) TableName() string {
	return "user"
}

func (u *User) Query(query UserQuery) ([]User, int64, error) {
	users := make([]User, 0)
	s := app.DB().Table("user")

	if query.Code != "" {
		s.Where("code=?", query.Code)
	}

	if query.Name != "" {
		s.Where("name=?", query.Name)
	}

	total, err := s.Limit(query.Limit, query.Offset).OrderBy("id desc").FindAndCount(&users)
	if err != nil {
		middlewares.Logger.Println("ERROR - User Query failed ", err)
		return nil, 0, errors.New("获取用户列表失败")
	}

	return users, total, nil
}

func (u *User) Insert() (*User, error) {
	_, err := app.DB().Insert(u)
	if err != nil {
		middlewares.Logger.Println("insert user fail", err)
		return nil, err
	}
	return u, err
}

func (u *User) Update() (*User, error) {
	_, err := app.DB().ID(u.Id).Cols("dept_sn", "dept_name", "mobile").Update(u)
	if err != nil {
		middlewares.Logger.Println("update user fail", err)
		return nil, err
	}
	fmt.Println(u.CreatedAt)
	return u, err
}

func (rm *User) FindByCode(code string) (*User, bool, error) {
	u := &User{}
	has, err := app.DB().Where("code=?", code).Get(u)
	//if has {
	//  accompany := &Accompany{}
	//  _, err := app.DB().Table("accompany").Where("code=?", code).Get(accompany)
	//  if err != nil {
	//    return nil, false, err
	//  }
	//  u.AccompanyUnitSn = accompany.UnitSn
	//}
	if err != nil {
		middlewares.Logger.Println("find by mobile doctor", err)
		return nil, false, err
	}
	return u, has, err
}

func (um *User) FindById(id int64) (*User, bool, error) {
	u := &User{}
	has, err := app.DB().ID(id).Get(u)
	if err != nil {
		middlewares.Logger.Println("find by id doctor", err)
		return nil, false, err
	}
	return u, has, err
}
